package server.service;

import server.mapper.MappedContext;
import server.mapper.MappedHost;
import server.mapper.MappedWrapper;
import server.model.Request;
import server.model.Response;
import server.servlet.impl.HttpServlet;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private List<MappedHost> mappedHostList;

    public RequestProcessor(Socket socket, List<MappedHost> mappedHostList) {
        this.socket = socket;
        this.mappedHostList = mappedHostList;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String appBase = null;

            for (MappedHost mappedHost : mappedHostList) {
                if(request.getHostName().equalsIgnoreCase(mappedHost.getHostName())){
                    //项目基础路径
                    appBase = mappedHost.getAppBase();
                    //从请求路径中的第一个路径获取context，例如/demo1/lagou中的/demo1
                    String[] split = request.getUrl().split("\\/");
                    String contextName = "/" + split[1];
                    //获取:/lagou
                    String urlPattern = request.getUrl().substring(contextName.length());
                    for (MappedContext mappedContext : mappedHost.getMappedContextList()) {
                        if(mappedContext.getPath().equalsIgnoreCase(contextName)){
                            for (MappedWrapper mappedWrapper : mappedContext.getMappedWrapperList()) {
                                if(mappedWrapper.getUrlPattern().equalsIgnoreCase(urlPattern)){
                                    mappedWrapper.getServlet().service(request, response);
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            response.outputHtml(appBase + request.getUrl());
            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
